import frappe
from frappe.database import utils
from frappe.query_builder.builder import MariaDB, Postgres
from frappe_dm.query_builder.builder import Dm
from frappe_dm.overrides.global_search import apply_global_search_patches
from frappe_dm.overrides.db_query import patch_db_query
from frappe_dm.database import patch_database
from frappe_dm.overrides.query_builder import patch_query_builder
from frappe_dm.overrides.sequence import patch_sequence, revert_sequence_patches
from frappe_dm.overrides.user_settings import patch_user_settings, revert_user_settings_patches
from frappe_dm.overrides.report import patch_reports
from frappe_dm.overrides.model import patch_model
from frappe_dm.overrides.make_random import apply_make_random_patches
from frappe_dm.overrides.password import apply_password_patches
from frappe_dm.overrides.website_analytics import override_website_analytics
from frappe_dm.overrides.connections import patch_connections, revert_connections_patches


def apply_patches():
    """应用达梦数据库补丁"""
    print("开始应用达梦数据库补丁...")
    
    patch_connections()
    # 扩展 Query 类型定义
    if not hasattr(utils, '_original_Query'):
        utils._original_Query = utils.Query
        utils.Query = str | MariaDB | Postgres | Dm
    
    # 应用查询构建器补丁
    patch_query_builder()

    # 应用数据库查询补丁
    print("应用数据库查询补丁...")
    patch_db_query()

    # 应用数据库补丁
    print("应用数据库补丁...")
    patch_database()
    
    # 应用序列补丁
    print("应用序列补丁...")
    patch_sequence()
    
    # 应用用户设置补丁
    print("应用用户设置补丁...")
    patch_user_settings()

    # 应用报表补丁
    print("应用报表补丁...")
    patch_reports()

    # 应用模型补丁
    print("应用模型补丁...")
    patch_model()

    # 应用全局搜索补丁
    print("应用全局搜索补丁...")
    apply_global_search_patches()

    # 应用随机数据生成补丁
    print("应用随机数据生成补丁...")
    apply_make_random_patches()

    # 应用密码相关补丁
    print("应用密码相关补丁...")
    apply_password_patches()

    # 应用网站分析补丁
    print("应用网站分析补丁...")
    override_website_analytics()

    print("达梦数据库补丁应用完成")

def revert_patches():
    """恢复原始补丁"""
    # 恢复用户设置补丁
    revert_connections_patches()
    
    revert_user_settings_patches()
    
    # 恢复序列补丁
    revert_sequence_patches()
    
    # 恢复 Query 类型定义
    if hasattr(utils, '_original_Query'):
        utils.Query = utils._original_Query
        del utils._original_Query
    
    # 恢复原始的枚举类型
    from frappe.query_builder.utils import db_type_is as original_db_type_is
    import frappe.query_builder.utils
    frappe.query_builder.utils.db_type_is = original_db_type_is
    
    # 恢复原始的 get_query_builder 函数
    from frappe.query_builder import get_query_builder
    frappe.query_builder.get_query_builder = get_query_builder
    frappe.query_builder.utils.get_query_builder = get_query_builder
